import { LOGIN } from '../actionTypes';
import fetch from '../utils/fetch';
import config from '../config';
import { message } from 'antd';

export const update = (payload) => ({
  type: LOGIN,
  payload,
});

export const change = (key, value) => (dispatch) => {
  dispatch(update({
    [key]: value,
  }));
};

export const checkLogin = async (type = 1) => {
  const token = localStorage.getItem(`token-${type}`);
  if (!token) {
    return false;
  }

  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/auth/check?type=${type}`,
    headers: {
      authorization: token,
    },
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    localStorage.setItem(`user-${type}`, JSON.stringify(res.data));
    return true;
  }
  return false;
};

/**
 * 登录
 * @param username
 * @param password
 */
export const login = (username, password) => async (dispatch, getState) => {
  const { type, username, password } = getState().login;
  if (!username || !password) {
    return false;
  }
  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/auth/login?type=${type}`,
    param: {
      username, password,
    }
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    const { uid, token } = res.data;
    message.success('登录成功', 3);
    localStorage.setItem(`token-${type}`, token);
    setTimeout(() => {
      +type === 0
        ? location.replace('#/admin')
        : location.replace(`#/my?uid=${uid}`)
    }, 3000);
  } else {
    message.error(res.msg || '用户名或者密码不正确');
  }
};
